/**
 * Article controller
 */
const mongoose = require('mongoose')
const Article = mongoose.model('Article')
const Comment = mongoose.model('Comment')
const Log = mongoose.model('Log')
const _ = require('lodash')
const markdown = require('markdown-it')
const LogMethods = require('./log')

const {
    baiduSeoPush
} = require('../utils').baiduSeo

// 新建文章
const createArticle = async(ctx, next) => {
    const article = ctx.request.body
    const tags = article.tags.filter(item => item)
    if (!article.title) {
        return ctx.body = {
            success: false,
            message: '文章标题不能为空'
        }
    }
    if (!article.content) {
        return ctx.body = {
            success: false,
            message: '文章内容不能为空'
        }
    }

    let arcTest = await Article.findOne({
        title: article.title
    })

    if (arcTest) {
        return ctx.body = {
            success: false,
            message: '文章标题不得重复'
        }
    }

    let result
    article.author_id = ctx.session.userid
    try {
        result = await new Article(article).save()
        ctx.body = {
            success: true,
            message: '创建成功',
            data: result._id,
            tags: tags || []
        }
        LogMethods.createLog(ctx.session.userid, 'NEW_ARTICLE', `新建了一片文章，标题为${article.title}`)
    } catch (e) {
        ctx.throw(400, e.toString())
    }
}

const getArticle = async(ctx, next) => {
	const _id = ctx.params.id
	try {
		let result = await Article.findById(_id, 'title content _id').populate('comment', 'content name likes state email _id').populate('tags')
		ctx.body = {
			success: true,
			data: result
		}
	} catch(e) {
		ctx.throw(400, '获取文章内容失败')
	}
}

const deleteArticle = async(ctx, next) => {
    const id = ctx.params.id
    try {
        await Article.findByIdAndRemove(id)
        await Comment.remove({
            article_id: id
        })
        ctx.body = {
            success: true,
            message: '删除成功'
        }
        LogMethods.createLog(ctx.session.userid, 'DELETE_ARTICLE', `删除了文章${id}`)
    } catch (e) {
        ctx.throw(400, '删除失败')
    }
}

const updateArticle = async(ctx, next) => {
    const article = ctx.request.body
    if (!article.title) {
        return ctx.body = {
            success: false,
            message: '文章标题不能为空'
        }
    }
    if (!article.content) {
        return ctx.body = {
            success: false,
            message: '文章内容不能为空'
        }
    }
    const id = ctx.params.id
    if (ctx.request.body._id) {
        delete ctx.request.body._id
    }
    try {
        await Article.findByIdAndUpdate(id, {
        	$set: {
        		title: article.title,
        		content: article.content,
        		tags: article.tags.filter(item => item)
        	}
        })
        ctx.body = {
            success: true,
            message: '更新成功'
        }
        LogMethods.createLog(ctx.session.userid, 'UPDATE_ARTICLE', `更新了文章${id}`)
    } catch (e) {
    	console.log(e)
        ctx.throw(400, '更新失败')
    }
}


/**
 * server端获取文章列表
 */
const getArticlesList = async(ctx, next) => {
    let currentPage = (parseInt(ctx.query.currentPage) > 0) ? parseInt(ctx.query.currentPage) : 1
    let perPage = (parseInt(ctx.query.perPage) > 0) ? (parseInt(ctx.query.perPage) > 0) : 10
    let startRow = (currentPage - 1) * perPage
    try {
        const list = await Article.find().skip(startRow).limit(perPage).sort('publish_time')
        const count = await Article.count()
        ctx.body = {
            success: true,
            data: {
                list,
                count
            }
        }
    } catch (e) {
        ctx.throw(400, '查询错误')
    }
}

/**
 * frontend 获取文章列表
 */

const getFrontArticlesList = async(ctx, next) => {
    let currentPage = (parseInt(ctx.query.currentPage) > 0) ? parseInt(ctx.query.currentPage) : 1
    let perPage = (parseInt(ctx.query.perPage) > 0) ? (parseInt(ctx.query.perPage) > 0) : 10
    let startRow = (currentPage - 1) * perPage

    let condition = {
        status: {
            $gt: 0
        }
    }
    if (ctx.query.tag) {
        const tag = String(ctx.query.tag)
        condition = _.defaults(condition, {
            tags: {
                $elemMatch: {
                    $eq: tag
                }
            }
        })
    }
    try {
        const list = await Article.find(condition).select('title images visit_count comment_count like_count publish_time')
            .skip(startRow).limit(perPage).sort('publish_time')
        ctx.body = {
            success: true,
            data: {
                list
            }
        }
    } catch (e) {
        ctx.throw(400, e.toString())
    }
}

const getFrontArticle = async(ctx, next) => {
    const _id = ctx.params.id
    const md = new markdown({
        html: true
    })

    try {
        let result = await Article.findOne({ _id, status: 1}).populate('comments').populate('tags')
        if (!result) {
        	return ctx.body = {
        		success: false,
        		message: '没有此文章'
        	}
        }
        // 表示不需要的属性，此处result不需要images属性

        result.content = md.render(result.content)
        result.visit_count++
        await Article.update({
            _id
        }, {
            $inc: {
                visit_count: 1
            }
        })
        ctx.body = {
        	success: true,
            data: result.info
        }
    } catch (e) {
        ctx.throw(400, '文章获取错误')
    }
}

const getFrontArticlesCount = async(ctx, next) => {
    let condition = {
        status: {
            $gt: 0
        }
    }
    if (ctx.query.tag) {
        const tag = Number(ctx.query.tag)
        condition = _.defaults(condition, {
            tags: {
                $elemMatch: {
                    $eq: tag
                }
            }
        })
    }
    try {
        const count = await Article.find()
        ctx.body = {
            success: true,
            data: {
                count
            }
        }
    } catch (e) {
        ctx.throw(400, '获取文章总数失败')
    }
}

module.exports = {
    createArticle,
    getArticlesList,
    getArticle,
    getFrontArticlesList,
    getFrontArticle,
    getFrontArticlesCount,
    updateArticle,
    deleteArticle
}